package com.cash.channel.svc.util;

import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;

public class ImageUtil {

    public static File base64ToImage(String base64File) throws Exception {
        base64File = base64File.replaceAll("data:image/jpeg;base64,", "");
        base64File = base64File.replaceAll("data:image/png;base64,", "");
        base64File = base64File.replaceAll("data:image/jpg;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64File);
        String tmpPath = System.getProperty("java.io.tmpdir");
        String name = UUID.randomUUID().toString();
        File convertFile = new File(tmpPath.concat("/").concat(name) + ".jpg");
        OutputStream out = null;
        try {
            out = new FileOutputStream(convertFile);
            out.write(bytes);
            out.flush();
        } catch (FileNotFoundException e) {
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return convertFile;
    }

}
